package com.wispx.shortlink.project.service.impl;

import com.wispx.shortlink.project.service.ShortLinkGeneratorService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class ShortLinkGeneratorServiceImpl implements ShortLinkGeneratorService {

    private final StringRedisTemplate stringRedisTemplate;

    // 互斥锁，用于重置 Redis 缓存，获取 id
    private final Object lock = new Object();

    // 下一个可用 ID，初始值为 -1
    private long nextIdAvailable = -1;

    // 最大可用 ID
    private long maxIdAvailable = -1;

    // "short-link:short-link_id:id"
    @Override
    public void multiGenIDFromRedis(int count) {
        // 超过最大范围，重置
        if(maxIdAvailable + count >= (long) Math.pow(62,6)){
            stringRedisTemplate.opsForValue().set("short-link:short-link_id:id","0");
        }
        long lastInsertId = (long)stringRedisTemplate.opsForValue().increment("short-link:short-link_id:id", count);
        nextIdAvailable = lastInsertId - count + 1;
        maxIdAvailable = lastInsertId;
    }

    @Override
    public  long genID() {

        synchronized (lock){
            boolean needPoll = nextIdAvailable == -1 || nextIdAvailable > maxIdAvailable;
            if(!needPoll){
                return nextIdAvailable ++;
            }
        }

        // 没有可用的 ID
        // DLC
        if(nextIdAvailable == -1 || nextIdAvailable > maxIdAvailable){
            synchronized (lock){
                if(nextIdAvailable == -1 || nextIdAvailable > maxIdAvailable){
                    multiGenIDFromRedis(10000);
                }
            }
        }

        return genID();
    }

}
